const ejs = require("ejs");
const path = require("path");
const fs = require("fs");
const fse = require("fs-extra");

const html = "<div><%= user.name %></div>";

const options = {};

const data = {
  user: {
    name: "张三"
  }
};

// 返回compile function,用于解析html中的ejs模板
/* const template = ejs.compile(html, options);
const compiledTemplate = template(data);
console.log(compiledTemplate);

const renderedTemplate = ejs.render(html, data, options);
console.log(renderedTemplate); */

/* const renderFile = ejs.renderFile(
  path.join(__dirname, "../ejs/template.txt"),
  data,
  options
);
console.log(renderFile);
renderFile.then((res) => {
  console.log(res);
}); */

const data2 = {
  user: {
    name: "张三",
    nickname: "<p>ZAD</p>",
    copyright: "版权所有"
  }
};
ejs.fileLoader = function (filePath) {
  const content = fs.readFileSync(filePath).toString();
  return "<div style='color: red;'>from <%= user.copyright %></div>" + content;
};
ejs.renderFile(
  path.join(__dirname, "../ejs/template.txt"),
  data2,
  options,
  (err, file) => {
    const filePath = path.resolve(process.cwd(), "index2.html");
    console.log(file, filePath);
    fse.writeFileSync(filePath, file);
  }
);
